# 用户登录、注册

from flask import Blueprint, request
from libs.response import generate_response
from flask_restful import Resource, Api
from model.user import UserManager
from model import db
from forms.user import UserForm, LoginForm
from libs.auth import create_token, login
from sqlalchemy import or_

userapi_bp = Blueprint('userapi', __name__, url_prefix='/v1')
# Blueprint两个参数（'蓝图名字',蓝图所在位置',url前缀)，注意：url前缀对该蓝图下所有route都起作用
# 第二个参数：__name__'蓝图所在的模块或者包，一般为'__name__'变量
api = Api(userapi_bp)


class Register(Resource):
    # 测试成功
    def post(self):
        # 通过表单来接收数据
        # 都客户端传递过来的username，email，password，phone进行校验
        # 变量名需要与客户端传递过来的字段名一致
        data = request.json
        form = UserForm(data=data)
        # 验证通过，将数据入库
        if form.validate():
            UserManager.create_user(
                # username=data.get("username"),
                form.username.data,
                password=data.get("password"),
                email=data.get("email"),
                phone=data.get("phone")
            )
            return generate_response(message="add user success")
        else:
            return generate_response(message=form.errors)


# 数据验证  wtforms
class LoginView(Resource):
    def post(self):
        data = request.json
        form = LoginForm(data=data)
        user = form.validate()
        if user:
            # 验证通过，生成token
            token = create_token(user.id)
            return generate_response(data={"token": token})
        else:
            return generate_response(message=form.errors)


class ModifyUserinfo(Resource):
    @login
    def put(self, id):
        user = UserManager.query.get(id)
        # 用户是登陆状态就可以修改信息
        if id is not None:
            user.username = request.json.get("username")
            user.gender = request.json.get("gender")
            user.addr = request.json.get("addr")
            user.introduction = request.json.get("introduction")
            user.birthday = request.json.get("birthday")
            db.session.add(user)
            db.session.commit()
            return generate_response(message="update userinfo success")
        else:
            return generate_response(status_code=10001, message="user_id is not exist")


api.add_resource(LoginView, "/login")
api.add_resource(Register, "/register")
api.add_resource(ModifyUserinfo, "/modify/<int:id>")
